package main

import (
	"log"
	"net/http"
	"os"
	"strings"
)

func main() {
	log.Println("启动http服务器")
	http.HandleFunc("/healthz", healthzHandler)
	http.HandleFunc("/", defaultHandler)
	http.ListenAndServe(":80", nil)
}

func healthzHandler(w http.ResponseWriter, r *http.Request) {
	defer defaultLog(w, r)
	defaultOper(w, r)
	w.WriteHeader(200)
	w.Write([]byte("200"))
}
func defaultHandler(w http.ResponseWriter, r *http.Request) {
	defer defaultLog(w, r)
	defaultOper(w, r)
	w.Write([]byte("hello"))
}

func defaultOper(w http.ResponseWriter, r *http.Request) {

	//将请求的header复制到响应的header
	for s, strings := range r.Header {
		for _, s2 := range strings {
			w.Header().Add(s, s2)
		}
	}
	//将环境变量VERSION输出到响应header
	envVersion := os.Getenv("VERSION")
	if envVersion != "" {
		w.Header().Add("VERSION", envVersion)
	}
}

func defaultLog(_ http.ResponseWriter, r *http.Request) {
	log.Println("客户端 IP地址", strings.Split(r.RemoteAddr, ":")[0], "连接成功")
	log.Println("r.method:", r.Method)
	log.Println("r.path:", r.URL.Path)
	log.Println("r.header:", r.Header)
	log.Println("r.body:", r.Body)
}
